package cn.virens.database.serviceimpl.base.upload;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.io.FileUtil;
import cn.virens.database.common.BaseServiceImpl;
import cn.virens.database.common.ExampleWrapper;
import cn.virens.database.mysql.mapper.base.BaseUploadImageMapper;
import cn.virens.database.mysql.model.base.BaseUploadImage;
import cn.virens.database.service.base.upload.BaseUploadImageService;

/**
 * 图片管理 - base_upload_image
 *
 * @author Virens
 * @since  2018-08-25 11:04:40
 */
@Service
public class BaseUploadImageServiceImpl extends BaseServiceImpl<BaseUploadImageMapper, BaseUploadImage> implements BaseUploadImageService {
	private static final String CACHE_NAME = "upload-images-cache";

	public BaseUploadImageServiceImpl() {
		super(BaseUploadImage.class);
	}

	@Override
	public List<? extends BaseUploadImage> selectAll(Map<String, Object> param) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.excludeProperties("id");
		example.or((c) -> {
			c.andLike("code", criteriaLike(param, "code"));
			c.andLike("name", criteriaLike(param, "name"));
			c.andLike("mimeType", criteriaLike(param, "mimeType"));
		});

		return super.selectAll(param);
	}

	@Override
	@Transactional(readOnly = true)
	@Cacheable(value = CACHE_NAME, key = "#p0", unless = "#result == null")
	public BaseUploadImage selectOne(Serializable code) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andEqualTo("code", code);

		return mBaseMapper.selectOne(example);
	}

	@Override
	@Transactional(readOnly = false)
	@CacheEvict(value = CACHE_NAME, key = "#p0")
	public int delete(String code, String rootPath) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andEqualTo("code", code);

		BaseUploadImage temp = mBaseMapper.selectOne(example);
		if (temp != null && mBaseMapper.deleteByExample(example) > 0) {
			FileUtil.del(temp.getThumb(rootPath));
			FileUtil.del(temp.getPath(rootPath));

			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int delete(Serializable id) {
		return -1;
	}

	@Override
	public BaseUploadImage update(BaseUploadImage record) {
		return null;
	}
}
